<template>
  <a-upload name="file"
            :multiple="false"
            accept=".txt, .json"
            :showUploadList="false"
            :beforeUpload="beforeUpload"
            :customRequest="()=>{}"
            @change="handleChange">
    <a-button>
      <a-icon v-if="icon"
              :type="icon" />
      {{ text }}
    </a-button>
  </a-upload>
</template>

<script>

import PropTypes from '@zh/common-utils/prop-types'

export default {
  name: 'ZTextfileReader',
  props: {
    text: PropTypes.string.def('读取文件'),
    icon: PropTypes.string.def(undefined)
  },
  data () {
    return {
      accept: '.json,.txt'
    }
  },
  created () { },
  methods: {
    /**
     * 上传前验证文件大小及类型
     */
    beforeUpload (file) {
      return new Promise((resolve, reject) => {
        const suffix = file.name.toLowerCase().split('.').pop()
        if (!this.accept.includes(suffix)) {
          this.$notify.error(`不支持上传该文件类型`)
          return
        }
        resolve()
      })
    },
    handleChange (options) {
      const reader = new FileReader()
      reader.readAsText(options.file.originFileObj, 'UTF-8')
      reader.onload = (e) => {
        const content = e.target.result
        if (options.file.type === 'text/plain') {
          this.$emit('change', content)
        } else if (options.file.type === 'application/json') {
          try {
            this.$emit('change', JSON.parse(content))
          } catch {
            this.$notify.error(`无法解析该文件`)
          }
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>